/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 */

package com.huawei.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.vo.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 三方服务接口调用
 *
 * @since 2025.10.11
 */
@Service
public class ThirdPartyApiService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${third-party.api.matrix.url}")
    private String matrixUrl;

    @Value("${third-party.api.exchange.url}")
    private String exchangeUrl;

    /**
     * 调用第三方 API - GET 请求
     */
    public ApiResponse callThirdPartyApi(String url, Map<String, String> headers,
                                         Map<String, Object> params) {
        try {
            // 构建请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);

            if (headers != null) {
                headers.forEach(httpHeaders::set);
            }

            // 构建 URL 参数
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            if (params != null) {
                params.forEach((key, value) -> {
                    if (value != null) {
                        builder.queryParam(key, value.toString());
                    }
                });
            }

            HttpEntity<String> entity = new HttpEntity<>(httpHeaders);

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                builder.toUriString(),
                HttpMethod.GET,
                entity,
                String.class
            );

            return ApiResponse.success(response.getBody(), response.getStatusCodeValue());

        } catch (Exception e) {
            return ApiResponse.error("调用第三方接口失败: " + e.getMessage(), 500);
        }
    }

    /**
     * 调用第三方 API - POST 请求
     */
    public ApiResponse callThirdPartyApiPost(String url, Map<String, String> headers,
                                             Object requestBody) {
        try {
            // 构建请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);

            if (headers != null) {
                headers.forEach(httpHeaders::set);
            }

            String bodyJson = objectMapper.writeValueAsString(requestBody);
            HttpEntity<String> entity = new HttpEntity<>(bodyJson, httpHeaders);

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                entity,
                String.class
            );

            return ApiResponse.success(response.getBody(), response.getStatusCodeValue());

        } catch (Exception e) {
            return ApiResponse.error("调用第三方接口失败: " + e.getMessage(), 500);
        }
    }

    /**
     * getMatrix API 示例
     */
    public ApiResponse getMatrix(String serviceType) {
        String url;
        switch (serviceType) {
            case "dataset":
                url = matrixUrl + "/dataset/list";
                break;
            case "agent":
                url = matrixUrl + "/agent/intelligence_agent/list";
                break;
            case "registry":
                url = matrixUrl + "/registry/mcp/list";
                break;
            case "knowledge":
                url = matrixUrl + "/knowledge/kllib/list";
                break;
            default:
                url = matrixUrl + "/model_base/model/list";

        }
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", 1);
        params.put("pageSize", 10);
        params.put("statusList", List.of("2","3"));
        ApiResponse response = callThirdPartyApiPost(url, null, params);
        // 封装返回数据
        if (response.isSuccess()) {
            try {
                JsonNode jsonNode = objectMapper.readTree(response.getData().toString());
                MatrixInfo matrixInfo = new MatrixInfo();
                matrixInfo.setServiceType(serviceType);
                matrixInfo.setCount(jsonNode.path("data").path("count").asInt());
                return ApiResponse.success(matrixInfo, response.getCode());
            } catch (Exception e) {
                return ApiResponse.error("解析天气数据失败: " + e.getMessage(), 500);
            }
        }
        return response;
    }

    /**
     * 调用汇率 API 示例
     */
    public ApiResponse getExchangeRate(String fromCurrency, String toCurrency) {
        String url = exchangeUrl + "/" + fromCurrency;

        ApiResponse response = callThirdPartyApi(url, null, null);

        if (response.isSuccess()) {
            try {
                JsonNode jsonNode = objectMapper.readTree(response.getData().toString());
                double rate = jsonNode.path("rates").path(toCurrency).asDouble();

                ExchangeRate exchangeRate = new ExchangeRate();
                exchangeRate.setFromCurrency(fromCurrency);
                exchangeRate.setToCurrency(toCurrency);
                exchangeRate.setRate(rate);
                exchangeRate.setTimestamp(jsonNode.path("time_last_updated").asLong());

                return ApiResponse.success(exchangeRate, response.getCode());
            } catch (Exception e) {
                return ApiResponse.error("解析汇率数据失败: " + e.getMessage(), 500);
            }
        }

        return response;
    }

    // 数据封装类
    public static class MatrixInfo {
        private String serviceType;

        private Integer count;

        @Override
        public String toString() {
            return String.format("Matrix服务类型: %s, 上架的服务总数: %d个",
                serviceType, count);
        }

        public String getServiceType() {
            return serviceType;
        }

        public void setServiceType(String serviceType) {
            this.serviceType = serviceType;
        }

        public Integer getCount() {
            return count;
        }

        public void setCount(Integer count) {
            this.count = count;
        }
    }

    public static class ExchangeRate {
        private String fromCurrency;
        private String toCurrency;
        private Double rate;
        private Long timestamp;

        // getters and setters
        public String getFromCurrency() {
            return fromCurrency;
        }

        public void setFromCurrency(String fromCurrency) {
            this.fromCurrency = fromCurrency;
        }

        public String getToCurrency() {
            return toCurrency;
        }

        public void setToCurrency(String toCurrency) {
            this.toCurrency = toCurrency;
        }

        public Double getRate() {
            return rate;
        }

        public void setRate(Double rate) {
            this.rate = rate;
        }

        public Long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(Long timestamp) {
            this.timestamp = timestamp;
        }

        @Override
        public String toString() {
            return String.format("%s 到 %s 的汇率: %.4f", fromCurrency, toCurrency, rate);
        }
    }
}